#!/bin/bash

source ./dbsetup.properties

hbm_location=$app_adapter_location/modules/databaseadapter/src/main/resources/config

#test=$(xmllint --pattern "string(hibernate-configuration/session-factory/property[@name='hibernate.connection.password'])" $hbm_location/hibernate.cfg.xml)
passwordLine=$(echo "xpath string(hibernate-configuration/session-factory/property[@name='hibernate.connection.password'])" | xmllint --shell $hbm_location/hibernate.cfg.xml)
password=$(echo $passwordLine | sed -n 's/.*:\(.*\)\/.*/\1/p')
echo "password is >>>" $password
usernameLine=$(echo "xpath string(hibernate-configuration/session-factory/property[@name='hibernate.connection.username'])" | xmllint --shell $hbm_location/hibernate.cfg.xml)
username=$(echo $usernameLine | sed -n 's/.*:\(.*\)\/.*/\1/p')
echo "user name is >>>" $username
schemaLine=$(echo "xpath string(hibernate-configuration/session-factory/property[@name='hibernate.default_schema'])" | xmllint --shell $hbm_location/hibernate.cfg.xml)
schema=$(echo $schemaLine | sed -n 's/.*:\(.*\)\/.*/\1/p')
echo "created schema >>> " $schema

#remove whitespaces
password=$(echo "'$password'")
password=$(echo $password | sed -n 's/ //p' | sed -n 's/ //p')
username=$(echo $username | sed -e 's/^ *//g' -e 's/ *$//g')
mysql -u root -h ${db_host_name} -p${db_root_password} $schema << EOFMYSQL

drop user '${username}'@'${db_host_name}';
flush privileges;
CREATE USER '${username}'@'${db_host_name}' IDENTIFIED BY ${password};

drop schema ${schema};
create schema ${schema};

GRANT ALL ON SIP_DATA_SCHEMA.* TO '${username}'@'${db_host_name}';

EOFMYSQL


